const app = getApp()
// const API_URL_ADDRESSLIST = getApp().data.api_url + '/getAddressList'
import { requestApi } from '../../../api'
import {extend} from '../../../sdk/extend'
import fun_loop from '../util/fun_loop'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    index: '',
    refer: '',                  // 标识来源页
    identifyType: '0', // 是否需要补充身份信息 0:不需要 1:号码&照片 2:仅号码
    channel: '',
    addressList: [],       // 收货地址列表数据
    selectIndex: -1,       // 选中收货地址
    isSelect: false,       // 地址列表是否支持可选   
    selectedObj: null,      // 被选中地址信息
    isShow: false,           // 显示新增收货地址
    idNumList: []           // 显示加密后身份证ID
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const refer = options.refer || ''
    const channel = options.channel || 'wx_xcx'
    const identifyType = options.identifyType || '0'

    this.data.identifyType = identifyType
    this.data.refer = refer

    if (options.isSelect) {  
      this.data.isSelect = true
    }

    this.setData({
      refer: refer,
      channel: channel,
    })

    // 获取地址列表数据
    app.request({
      url: requestApi.addressListUrl
    }, data => {
      var data = this.handle(data) // 调用原后端处理数据逻辑方法
      var idList = []
      if (data.original.address_list) {
        data.original.address_list.forEach(item => {
          if (item.id_number != '') {
            idList.push(`${item.id_number.substr(0, 4)}********${item.id_number.substring(item.id_number.length - 6, item.id_number.length)}`)
          } else {
            idList.push('')
          }
        })
      }

      this.setData({
        addressList: data.original.address_list || [],
        isShow: true,
        idNumList: idList
      }) 

      // 存储storage
      wx.setStorage({
        key: 'addressList',
        data: data.original.address_list || [],
      })
    }, error => {
      wx.showModal({
        title: '提示',
        content: error,
        showCancel: false
      })
    })
    
    // 获取上次选择地址index
    wx.getStorage({
      key: 'selectIndex',
      success: (res) => {
        this.setData({
          selectIndex: res.data,
        })
      }
    })
  },

  chooseAddress() {
    wx.chooseAddress({
      success: (res) => {
        let param = {
          address: res.detailInfo,
          city: res.cityName,
          district: res.countyName,
          id_images: {},
          id_number: "",
          is_default: 0,
          mobilephone: res.telNumber,
          postcode: res.postalCode,
          province: res.provinceName,
          recipeint: res.userName,
          record_status: 1
        }
        app.request({
          url: requestApi.addressSaveUrl,
          data: param,
          method: 'POST'
        }, data => {
          let list = this.data.addressList

          for (let i = 0, len = list.length; i < len ; i++ ) {
            list[i]['is_default'] = 0
          }

          if (this.data.index != '') {  // 编辑
            let index = this.data.index
            list[index] = param;  
          } else {       // 新建
            param = extend({}, param, {id: data.original.addr_id})
            list.unshift(param)
          }

          // 同步存储storage
          try {
            wx.setStorageSync('addressList', list)
          } catch (e) {
            // 
          }

          // 微信获取的地址，直接更改收货地址
          let pages = getCurrentPages()
          let prevPage = pages[pages.length - 2] 
          this.setData({
            selectIndex: 0
          })
          wx.setStorage({
            key: 'selectIndex',
            data: 0,
          })
          prevPage.setData({                               
            addressData: list[0],
            addressIndex: 0,
          })
          
          wx.navigateBack()
        }, error => {
          wx.showModal({
            title: '提示',
            content: error,
            showCancel: false
          })
        }, () => {
          this.saveFlag = false
        })
      },
      fail: function(err) {
        console.log(err)
      }
    })
  },

  // 绑定选中事件
  selecteAddress: function (e) {
    let index = e.currentTarget.dataset.index
    let pages = getCurrentPages()
    let prevPage = pages[pages.length - 2] 
    this.setData({
      selectIndex: index
    })

    // 缓存上次选择地址index
    wx.setStorage({
      key: 'selectIndex',
      data: index,
    })
    
    if (this.data.isSelect) {   // 支付选地址时支持选中
      prevPage.setData({                               
        addressData: this.data.addressList[index],
        addressIndex: index,
      })
      wx.navigateBack({}) 
    }
  },
  // 新增收货地址
  addAddress: function () {
    wx.navigateTo({
      url: '../addressDetail/addressDetail?channel=' + this.data.channel + '&refer=' + this.data.refer + '&identifyType=' + this.data.identifyType
    })
  },
  // 编辑收货地址
  editAddress: function (e) {
    let index = e.currentTarget.dataset.index

    wx.navigateTo({
      url: '../addressDetail/addressDetail?index=' + index + '&channel=' + this.data.channel + '&refer=' + this.data.refer + '&identifyType=' + this.data.identifyType
    })
  },

  /**
   * 本期调整功能，地址列表无删除地址入口
   */
  // delete
  // delete: function (e) {
  //   let addrList = this.data.addressList
  //   let addrId = e.currentTarget.dataset.id
  //   let data = {
  //     'record_status': 0,
  //     'addr_id': addrId,
  //   }

  //   wx.showModal({
  //     title: '提示',
  //     content: '确认要删除收货地址吗？',
  //     success: (res) => {
  //       if (res.confirm) {
  //         app.request({
  //           url: requestApi.addressSaveUrl,
  //           data: data,
  //           method: 'POST'
  //         }, (data) => {
  //           if (data.original.status == 'success') {
  //             for (let i = 0; i < addrList.length; i++) {
  //               if (addrList[i].id == addrId) {
  //                 addrList.splice(i, 1)
  //               }
  //             }
  //             this.setData({
  //               addressList: addrList
  //             })
  //           }
  //         }, (error) => {
  //           wx.showModal({
  //             title: '提示',
  //             content: error,
  //             showCancel: false
  //           })
  //         })
  //       } else if (res.cancel) {
  //       }
  //     }
  //   })
  // },

  /**
   * 本期调整功能，地址列表无设置默认地址入口
   */
  // 设为默认地址 
  // setDefault: function (e) {
  //   let addrList = this.data.addressList
  //   let addrId = e.currentTarget.dataset.id
  //   let data = {
  //     'record_status': 1,
  //     'addr_id': addrId,
  //     'is_default': 1,
  //   }
  //   app.request({
  //     url: requestApi.addressSaveUrl,
  //     data: data,
  //     method: 'POST'
  //   }, (data) => {
  //     if (data.original.status == 'success') {
  //       for (let i = 0; i < addrList.length; i++) {
  //         if (addrList[i].id == addrId) {
  //           addrList[i].is_default = 1
  //         } else {
  //           addrList[i].is_default = 0
  //         }
  //       }
  //       this.setData({
  //         addressList: addrList
  //       })
  //     }
  //   }, (error) => {
  //     wx.showModal({
  //       title: '提示',
  //       content: error,
  //       showCancel: false
  //     })
  //   })
  // },

  // 原后端->前端数据转换
  handle: function (data) {
    let address_list = data.original.address_list || []
    fun_loop(address_list)(function (index, value) {

      if (value.id_number) {
        value.id_number_cn = value.id_number.substr(0, 4) + '********' + value.id_number.substr(-6, 6)
      }
    })

    return data

  }
})